﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using IQKS.AWP.DataAccessLayer;
using IQKS.AWP.BusinessObject;
using IQKS.AWP.BusinessAccessLayer;
using System.Configuration;



public partial class Admin_BriefMasterModify : System.Web.UI.Page
{

    public string DocumentPath = ConfigurationSettings.AppSettings["BriefDoc"];
    public string GDDocumentPath = ConfigurationSettings.AppSettings["GDDoc"];

    
    Int32 FileLimitSize = Convert.ToInt32(ConfigurationManager.AppSettings["FileLimitSize"].ToString());
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try 
            {
                CalendarExtender1.Format = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat.ShortDatePattern;
                mdlStartDate.Format = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB").DateTimeFormat.ShortDatePattern;
                lblBriefDocument.Text = "* Acceptable file formats " + Convert.ToString(ConfigurationManager.AppSettings["BriefFileType"]).Replace("|", ",") + Convert.ToString(ConfigurationManager.AppSettings["FileSize"]);
                lblGDDocument.Text = "* Acceptable file formats " + Convert.ToString(ConfigurationManager.AppSettings["BriefFileType"]).Replace("|", ",") + Convert.ToString(ConfigurationManager.AppSettings["FileSize1"]);
                GetCountryMaster();
                if (Request.QueryString.Count > 0) //add
                {
                    if (Convert.ToString(Request.QueryString["bgid"]) == "0")
                    {
                        lblTitle.Text = "Add New Brief";
                        trDownloadBrief.Visible = false;
                        trDownloadGD.Visible = false;
                        ClearData();
                    }
                    else //edit
                    {
                        lblTitle.Text = "Update Brief";
                        GetData(Convert.ToInt64(Request.QueryString["bgid"]));
                        trDownloadBrief.Visible = true;
                        trDownloadGD.Visible = true;
                    }
                }
            }
            catch (Exception)
            {
                Response.Redirect("~/Admin/BriefMaster.aspx");
            }
        }
        txtBriefSDate.Attributes.Add("readonly", "readonly");
        txtBriefEDate.Attributes.Add("readonly", "readonly");
    }

    private void ClearData()
    {
        txtBriefTitle.Text = string.Empty;
        txtBriefDescription.Text = string.Empty;
        txtBriefSDate.Text = string.Empty;
        txtBriefEDate.Text = string.Empty;
        chkIsactive.Checked = false;
        lblMessage.Text = string.Empty;
    }

    private void GetData(Int64 intBriefID)
    {
        BriefMasterBAL objBMBal = new BriefMasterBAL();
        BriefMasterBO objBMBO = new BriefMasterBO();
        objBMBO = objBMBal.GetBriefMaster(intBriefID);

        if (objBMBO != null)
        {

            txtBriefTitle.Text = objBMBO.BriefTitle;
            txtBriefDescription.Text = objBMBO.BriefDesc;
            txtBriefSDate.Text = Convert.ToString(objBMBO.BriefStartDate.ToString("dd/MM/yyyy"));
            txtBriefEDate.Text = Convert.ToString(objBMBO.BriefEndDate.ToString("22/10/2015"));
            ddlCountryName.SelectedValue = Convert.ToString(objBMBO.CountryID);
            chkIsactive.Checked = Convert.ToBoolean(objBMBO.IsActive);
            string strPathBrief = string.Empty;
            string strPathGD = string.Empty;
            string strCvTitle = Convert.ToString(objBMBO.DocumentName);
            string strGDTitle = Convert.ToString(objBMBO.GDDocumentName);


            
            string strAuthority = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath;
            string strUCvpath = DocumentPath.Remove(0, 1);
            string strGDvpath = GDDocumentPath.Remove(0, 1);
            strPathBrief = strAuthority + strUCvpath + strCvTitle;
            strPathGD = strAuthority + strGDvpath + strGDTitle;
            if (strCvTitle != "")
            {
                tdUploadBriefDoc.InnerHtml = "<a href=javascript:onClickLink('" + strPathBrief + "')>" + "<b>Click Here</b>" + "</a>";
            }
            else
            { 
                tdUploadBriefDoc.InnerHtml="No Brief document uploaded."; 
            }
            RequiredFieldValidator5.Enabled = false;
            if (strGDTitle != "")
            {
                tdUploadGDDoc.InnerHtml = "<a href=javascript:onClickLink('" + strPathGD + "')>" + "<b>Click Here</b>" + "</a>";
            }
            else
            {
                tdUploadGDDoc.InnerHtml = "No GD document uploaded.";
            }
            RequiredFieldValidator3.Enabled = false;
        }
    }

    private void GetCountryMaster()
    {
        ddlCountryName.DataSource = GetCountryMasterDataSet();
        ddlCountryName.DataTextField = "CountryName";
        ddlCountryName.DataValueField = "CountryID";
        ddlCountryName.DataBind();
        ddlCountryName.Items.Insert(0, new ListItem("-- Select Country Name --", "0"));
    }

    private DataSet GetCountryMasterDataSet()
    {

        DataSet objDs=null;
        try
        {
            objDs = new CountryMasterBAL().GetCountryMaster();
        }
        catch (Exception exception)
        {
            exception.AddErrorToLog(); //throw new ApplicationException(exception.Message);
        }
        return objDs;

    }
    protected void DDCountryName_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {


        string strPathBrief = string.Empty;
        string strPathGD = string.Empty;
        string strFileExtBrief = string.Empty;
        string strFileExtGD = string.Empty;
        string strFileName = string.Empty;
        string strFullFileBriefName = string.Empty;
        string strFullFileGDName = string.Empty;
        strFileExtBrief = Path.GetExtension(txtUploadDoc1.PostedFile.FileName);
        strFileExtGD = Path.GetExtension(txtUploadDoc2.PostedFile.FileName);
        string strDateCon = Convert.ToString(System.DateTime.Now.ToShortDateString());
        string strDateYY = System.DateTime.Now.ToShortDateString();
        string strDateMM = CommonUtility.ConvertDateToddMMYYY_hhmmss(System.DateTime.Now.ToString());
        string strYYYY = strDateYY.Replace("/", "_");
        string strYYYYM = strDateMM.Remove(0, 11);
        string strYYYYMM = strYYYYM.Replace(":", "_");
        string strDateConYYMM = strYYYY + strYYYYMM;
        if (txtUploadDoc1.HasFile)
        {
            strFileName = txtUploadDoc1.FileName.Replace(Convert.ToString(txtUploadDoc1.FileName), txtBriefTitle.Text.Trim());

            strFullFileBriefName = strFileName + "_" + strDateConYYMM + strFileExtBrief;
        }
        strFullFileBriefName = strFullFileBriefName.Replace(" ", "_").Replace("'", "_");
        if (txtUploadDoc2.HasFile)
            
        {
            strFileName = txtUploadDoc2.FileName.Replace(Convert.ToString(txtUploadDoc2.FileName), txtBriefTitle.Text.Trim());

            strFullFileGDName = strFileName + "_" + strDateConYYMM + strFileExtGD;
        }

        strFullFileGDName = strFullFileGDName.Replace(" ", "_").Replace("'", "_");
        //string strStartDate = CommonUtility.ConvertDateToMMddyyyy(txtBriefSDate.Text.Trim());
        //string strEndDate = CommonUtility.ConvertDateToMMddyyyy(txtBriefSDate.Text.Trim());
        
        if (Page.IsValid)
        {
            if (Request.QueryString.Count > 0)
            {
                BriefMasterBAL objBMBal;
                BriefMasterBO objBMBO;
                Guid gudUserID = CommonUtility.GetLoggedOnUserId();
                int intBgid = Convert.ToInt16(Request.QueryString["Bgid"]);
                string strmod = Convert.ToString(Request.QueryString["mod"]);
                string strReturnValue;
                if (strmod == "in")//add
                {
                    objBMBal = new BriefMasterBAL();
                    objBMBO = new BriefMasterBO();
                    //if (txtUploadDoc.HasFile)
                    //{
                    //    //TODO Add As per physical file
                    //    //create the path to save the file to
                    //    string fileName = Path.Combine(Server.MapPath(DocumentPath), txtUploadDoc.FileName);
                    //    //save the file to our local path
                    //    txtUploadDoc.SaveAs(strFullFileName);
                    //}
                    objBMBO.DocumentName = strFullFileBriefName;
                    objBMBO.GDDocumentName = strFullFileGDName;

                    objBMBO.SetMethod = "INSERT";
                    objBMBO.BriefID = 0;
                    objBMBO.CountryID = Convert.ToInt32(ddlCountryName.SelectedValue.Trim());
                    objBMBO.BriefTitle = txtBriefTitle.Text.Trim();
                    objBMBO.BriefDesc = txtBriefDescription.Text.Trim();
                    objBMBO.StBriefStartDate = Convert.ToDateTime(txtBriefSDate.Text.Trim());
                    //objBMBO.StBriefEndDate = Convert.ToDateTime(txtBriefEDate.Text.Trim());
                    objBMBO.StBriefEndDate = Convert.ToDateTime("22/10/2015");
                    if (txtUploadDoc1.HasFile)
                    {
                        if (txtUploadDoc1.PostedFile.FileName != "")
                        {
                            BriefFileSave(strFullFileBriefName);
                        }
                    }
                    if (txtUploadDoc2.HasFile)
                    {
                        if (txtUploadDoc2.PostedFile.FileName != "")
                        {
                            GDFileSave(strFullFileGDName);
                        }
                    }
                    objBMBO.CreatedBy = gudUserID;
                    objBMBO.ModifyBy = gudUserID;
                    objBMBO.ModifyDate = System.DateTime.Today;
                    objBMBO.IsActive = Convert.ToBoolean(chkIsactive.Checked);
                    strReturnValue = (string)objBMBal.SetBriefMaster(objBMBO);
                    if (strReturnValue == "SUCCESS")
                    {
                        ClearData();
                        //lblMessage.Text = "Brief has been save succesfully.";
                        //lblMessage.ForeColor = System.Drawing.Color.Green;
                        //Response.Redirect("BriefMaster.aspx");

                        //string script = "window.onload = function(){window.location = 'BriefMaster.aspx'; alert('Brief has been save succesfully.'); }";
                        //ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true); 
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Brief has been save succesfully.');", true);
                    }
                    else if (strReturnValue == "EXIST")
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Brief already exists.');", true);
                        //lblMessage.Text = "Brief already exists."; //EnrollResources.GetMessage(Message.InsertMessage); //   
                        //lblMessage.ForeColor = System.Drawing.Color.Red;
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Error while saving Brief.');", true);
                        //lblMessage.Text = "Error while saving Brief."; //EnrollResources.GetMessage(Message.FailedMessage); // 
                        //lblMessage.ForeColor = System.Drawing.Color.Red;
                    }
                }
                else if (strmod == "up")
                {
                    objBMBal = new BriefMasterBAL();
                    objBMBO = new BriefMasterBO();
                    objBMBO.SetMethod = "UPDATE";
                    objBMBO.BriefID = intBgid;
                    objBMBO.CountryID = Convert.ToInt32(ddlCountryName.SelectedValue.Trim());
                    objBMBO.BriefTitle = txtBriefTitle.Text.Trim();
                    objBMBO.BriefDesc = txtBriefDescription.Text.Trim();
                    string strDateS = txtBriefSDate.Text.Trim();
                    string strDateE = "22/10/2015";
                    objBMBO.StBriefStartDate = Convert.ToDateTime(txtBriefSDate.Text.Trim());
                    objBMBO.StBriefEndDate = Convert.ToDateTime("22/10/2015");
                    if (txtUploadDoc1.HasFile)
                    { 
                        if (txtUploadDoc1.PostedFile.FileName != "")
                        {
                            BriefFileSave(strFullFileBriefName);
                        }
                    }
                    objBMBO.DocumentName = strFullFileBriefName.Replace(" ", "");
                    if (txtUploadDoc2.HasFile)
                    {
                        if (txtUploadDoc2.PostedFile.FileName != "")
                        {
                            GDFileSave(strFullFileGDName);
                        }
                    }
                    objBMBO.GDDocumentName = strFullFileGDName.Replace(" ", "");

                    
                    objBMBO.ModifyBy = gudUserID;
                    objBMBO.ModifyDate = System.DateTime.Today;
                    objBMBO.IsActive = Convert.ToBoolean(chkIsactive.Checked);
                    strReturnValue = (string)objBMBal.SetBriefMaster(objBMBO);
                    if (strReturnValue == "SUCCESS")
                    {
                        //lblMessage.Text = "Brief has been updated succesfully.";
                        //lblMessage.ForeColor = System.Drawing.Color.Green;
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Brief has been updated succesfully.');", true);
                    }
                    else if (strReturnValue == "EXIST")
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Brief already exists.');", true);
                        //lblMessage.Text = "Brief already exists."; //EnrollResources.GetMessage(Message.InsertMessage); //    
                        //lblMessage.ForeColor = System.Drawing.Color.Red;
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Error while saving Brief.');", true);
                        //lblMessage.Text = "Error while saving Brief."; //EnrollResources.GetMessage(Message.FailedMessage); // 
                        //lblMessage.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }
        }
    }
    private void BriefFileSave(string strFullFileName)
    {
        string strPathBrief = string.Empty;
        
        //string strDateCon = Convert.ToString(System.DateTime.Now.ToShortDateString());
        
        //string strDateYY = CommonUtility.ConvertDateToMMddyyyy(strDateCon);
        //string strDateMM = CommonUtility.ConvertDateToddMMYYY_hhmmss(strDateCon);

        strPathBrief = MapPath(Convert.ToString(ConfigurationManager.AppSettings["BriefDoc"]));
        hdnUploadPic.Value = strPathBrief + strFullFileName;
        //txtUploadDoc1.SaveAs(hdnUploadPic.Value);
        CommonUtility.SaveFile(txtUploadDoc1, strPathBrief, strFullFileName);

        string strProfileFilePath = string.Empty;
        strProfileFilePath = MapPath(Convert.ToString(ConfigurationManager.AppSettings["BriefDoc"]) + System.IO.Path.GetFileName(hdnUploadPic.Value));

        //if (File.Exists(Path.Combine(strProfileFilePath, hdnUploadPic.Value)))
        //{
        //    File.Delete(strProfileFilePath);
        //}
        //File.Move(hdnUploadPic.Value, strProfileFilePath);
    }
    private void GDFileSave(string strFullFileName)
    {
        string strPathGD = string.Empty;

        //string strDateCon = Convert.ToString(System.DateTime.Now.ToShortDateString());

        //string strDateYY = CommonUtility.ConvertDateToMMddyyyy(strDateCon);
        //string strDateMM = CommonUtility.ConvertDateToddMMYYY_hhmmss(strDateCon);

        strPathGD = MapPath(Convert.ToString(ConfigurationManager.AppSettings["GDDoc"]));
        hdnUploadPic2.Value = strPathGD + strFullFileName;        
        //txtUploadDoc2.SaveAs(hdnUploadPic2.Value);
        CommonUtility.SaveFile(txtUploadDoc2, strPathGD, strFullFileName);

        string strProfileFilePath = string.Empty;
        strProfileFilePath = MapPath(Convert.ToString(ConfigurationManager.AppSettings["GDDoc"]) + System.IO.Path.GetFileName(hdnUploadPic2.Value));

        //if (File.Exists(Path.Combine(strProfileFilePath, hdnUploadPic.Value)))
        //{
        //    File.Delete(strProfileFilePath);
        //}
        //File.Move(hdnUploadPic.Value, strProfileFilePath);
    }
    protected void btnCancel_OnClick(object sender, EventArgs e)
    {
        if (Request.QueryString.Count > 0) //add
        {
            if (Convert.ToString(Request.QueryString["bgid"]) == "0")
            {
                ClearData();
                Response.Redirect("~/Admin/BriefMaster.aspx");
            }
            else
            {
                lblMessage.Text = string.Empty;
                GetData(Convert.ToInt64(Request.QueryString["bgid"]));
                Response.Redirect("~/Admin/BriefMaster.aspx");
            }

        }
    }

    protected void BriefMasterResume_ServerValidate(object source, ServerValidateEventArgs args)
    {

        int fileSize = txtUploadDoc1.PostedFile.ContentLength;

        if (fileSize > (FileLimitSize))
        {
            args.IsValid = false;
           // cstBriefMasterResume.ErrorMessage = "Resume document size should not be more than 5 MB.";
            return;
        }
        //FileSize1

        int fileSize1 = txtUploadDoc2.PostedFile.ContentLength;

        if (fileSize1 > (FileLimitSize))
        {
            args.IsValid = false;
           // cstBriefMasterResume.ErrorMessage = "Resume document size should not be more than 5 MB.";
            return;
        }
    }
}